function getUrl(){
    var url = window.location.href;
    var path = window.location.pathname;
    var search = window.location.search;
    url = url.replace(path,"/");
    url = url.replace(search,"")
    return url;
}

$(document).ready(function () {
    const url = getUrl();

    $.ajax({
        url:url+"adminInfo/getPeers",
        data:{},
        type: "get",
        contentType: "application/json",
        success: function(map) {
            console.log(map);
            
            $("#pwd").text(map.pwd);

            if(!($.isEmptyObject(map.ws))){

                $.each(map.ws, function (i, ws) {
                    console.log(ws);

                    const mode =
                    '<tr>'+
                        '<td id="adr"></td>'+
                        '<td>'+
                            '<a class="btn btn-danger" id="peerDelete">'+
                                '<i class="halflings-icon white trash"></i> '+
                            '</a>'+
                        '</td>'+
                    '</tr>';

                    const $obj = $(mode);
                    $obj.find("#adr").text(ws);

                    $("#peers").append($obj);
                })



            }
        },
        error:function(){
            console.log("----------")
        }
    })

    $("#peerBody").on('click','#peerDelete',function(){
        const address = $(this).parent().parent().find("#adr").text();
        console.log(address);
        const url = getUrl();

        $.ajax({
            url:url+"adminInfo/peerClose",
            data:{
                address:address
            },
            type: "get",
            contentType: "application/json",
            success: function(map) {
                location.href="peer.html";
            },
            error:function(){
                console.log("----------")
            }
        })
    });
})

$("#addPeer").click(function () {
    const url = getUrl();
    const peer = $("#peerAddres").val();
    const pwd = $("#peerPwd").val();

    const data ={
        "peer":peer,
        "pwd":pwd
    }


    $.ajax({
        url:url+"adminInfo/addPeer",
        data:JSON.stringify(data),
        type: "post",
        contentType: "application/json; charset=utf-8",
        success: function(map) {
            location.href="peer.html";
        },
        error:function(){
            console.log("----------")
        }
    })
})